package com.diandi.code.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 袁恩光 on 2018/5/7.
 */
public class FreemarkerUtil {

    private static final Logger logger = LoggerFactory.getLogger(FreemarkerUtil.class);

    private static final String TEMPLATE_PATH = "/template";

    private static final String MODEL_NAME = "modelName";


    /**
     * 根据模板名称创建 stream
     *
     * @param templateName 模板名称
     * @param param        创建模板时需要的参数
     * @return 返回 stream
     */
    public static ByteArrayOutputStream createStream(String templateName, Map<String, String> param) {
        logger.debug("freemarker outputStream构建开始");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            Writer out = new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"));
            Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            cfg.setClassForTemplateLoading(FreemarkerUtil.class, TEMPLATE_PATH);
            logger.debug("读取freemarker模板");
            Template t = cfg.getTemplate(templateName);
            logger.debug("依据freemarker生成内容");
            t.process(param, out);
            out.flush();
            out.close();
            logger.debug("freemarker outputStream构建结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stream;
    }


    /**
     * 同上
     *
     * @param templateName 模板名称
     * @param value        变量值
     * @return stream
     */
    public static ByteArrayOutputStream createStream(String templateName, String value) {
        Map<String, String> param = new HashMap<>();
        param.put(MODEL_NAME, value);
        return createStream(templateName, param);
    }


}
